package felix.dataviewer.Model;

import android.text.TextUtils;
import android.util.Log;

import felix.dataviewer.Util.Constants;
import felix.felixlib.util.SPUtil;


/**
 * Created by huangmf on 7/28/2017.
 */

public class FilterModule {
    private final static String TAG = FilterModule.class.getSimpleName();
    private final static String SPLIT = "_";
    public static String[] getAppFiter() {
        String str = SPUtil.getStringValue(Constants.SP.KEY_APP_FILTER, "");
        return str.split(SPLIT);
    }

    public static void putAppFilter(String str) {
        if (TextUtils.isEmpty(str)) {
            Log.w(TAG, "putAppFilter: empty string can't be as a filter.");
            return;
        }
        str = str.toLowerCase();
        String[] filters = getAppFiter();
        for (String filter : filters) {
            if (filter.equals(str)) {
                Log.w(TAG, "putAppFilter: " + str + " is aready in the filters,ignore.");
                return;
            }
        }
        String previous = toFilterString(filters);
        if (TextUtils.isEmpty(previous)) {
            previous = str;
        } else {
            previous = previous + SPLIT + str;
        }
        SPUtil.putStringValue(Constants.SP.KEY_APP_FILTER, previous);
    }

    /**
     * 将过滤字符串专程字符串
     * @param filters
     * @return
     */
    private static String toFilterString(String[] filters) {
        if (filters == null) {
            Log.w(TAG, "toFilterString: strs is null.");
            return "";
        }
        final int length = filters.length;
        if (length == 0) {
            Log.w(TAG, "toFilterString: strs is empty.");
            return "";
        } else if (length == 1) {
            return filters[0];
        }
        StringBuilder sb = new StringBuilder(filters[0]);
        for (int i = 1; i < length; i++) {
            sb.append(SPLIT).append(filters[i]);
        }
        return sb.toString();
    }
}
